package com.atguigu.service.impl;

import com.atguigu.entity.ProductImage;
import com.atguigu.entity.ProductSalePropertyKey;
import com.atguigu.entity.ProductSalePropertyValue;
import com.atguigu.entity.ProductSpu;
import com.atguigu.mapper.ProductSpuMapper;
import com.atguigu.service.ProductImageService;
import com.atguigu.service.ProductSalePropertyKeyService;
import com.atguigu.service.ProductSalePropertyValueService;
import com.atguigu.service.ProductSpuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author zhangqiang
 * @since 2021-08-24
 */
@Service
public class ProductSpuServiceImpl extends ServiceImpl<ProductSpuMapper, ProductSpu> implements ProductSpuService {
    @Autowired
    private ProductImageService productImageService;
    @Autowired
    private ProductSalePropertyKeyService propertyKeyService;
    @Autowired
    private ProductSalePropertyValueService propertyValueService;

    @Override
    public void saveProductSpu(ProductSpu productSpu) {
        //1.保存商品spu
        baseMapper.insert(productSpu);
        //2.保存商品spu对应的图片 product_image
        List<ProductImage> productImageList = productSpu.getProductImageList();
        if(!CollectionUtils.isEmpty(productImageList)){
            for (ProductImage productImage : productImageList) {
                //该图片归属于哪个spu商品
                productImage.setProductId(productSpu.getId());
            }
            productImageService.saveBatch(productImageList);
        }
        //冗余存储的目的减少多张表的查询 提高查询效率
        List<ProductSalePropertyKey> salePropertyKeyList = productSpu.getSalePropertyKeyList();
        //4.保存销售属性value的信息
        if(!CollectionUtils.isEmpty(salePropertyKeyList)){
            for (ProductSalePropertyKey salePropertyKey : salePropertyKeyList) {
                salePropertyKey.setProductId(productSpu.getId());
                //取出单个销售属性key所对应的value集合
                List<ProductSalePropertyValue> salePropertyValueList = salePropertyKey.getSalePropertyValueList();
                if(!CollectionUtils.isEmpty(salePropertyValueList)){
                    for (ProductSalePropertyValue salePropertyValue : salePropertyValueList) {
                        //告诉该销售属性value属于哪个spu
                        salePropertyValue.setProductId(productSpu.getId());
                        //告诉该销售属性value属于哪个销售属性key
                        salePropertyValue.setSalePropertyKeyName(salePropertyKey.getSalePropertyKeyName());
                    }
                    //批量保存销售属性value信息
                    propertyValueService.saveBatch(salePropertyValueList);
                }
            }
            //3.批量保存销售属性key的信息
            propertyKeyService.saveBatch(salePropertyKeyList);
        }
    }
}
